package cn.yx.framework.configuration;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.cache.support.CompositeCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;

/**
 * 缓存配置
 *
 * @author chenw
 * @email javacspring@gmail.com
 * @time 2016/11/09
 */
@Configuration
@ComponentScan(basePackages = "cn.com.yx.ms.service.impl")
@EnableCaching(proxyTargetClass = true)
@Import(DataSourceConfig.class)
public class CacheConfig implements CachingConfigurer {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private BaseConstant.RedisCacheConfig redisCacheConfig;

    @Override
    public CacheManager cacheManager() {
        CompositeCacheManager compositeCacheManager = new CompositeCacheManager();
        compositeCacheManager.setCacheManagers(new ArrayList<CacheManager>() {{
            add(redisCacheManager());
        }});
        //缓存失败则不使用缓存
        compositeCacheManager.setFallbackToNoOpCache(true);
        return compositeCacheManager;
    }

    @Override
    public CacheResolver cacheResolver() {
        return null;
    }

    @Override
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }

    @Override
    public CacheErrorHandler errorHandler() {
        return null;
    }

    @Bean
    public RedisCacheManager redisCacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        redisCacheManager.setDefaultExpiration(redisCacheConfig.getOvertime());
        redisCacheManager.setLoadRemoteCachesOnStartup(true);
        redisCacheManager.setTransactionAware(true);
        redisCacheManager.setCacheNames(new HashSet<String>() {{
            add("redis");
        }});
        return redisCacheManager;
    }

}
